<template>
  <div :class="prefixCls">
    <Card size="small" style="width: 100%">
      <template #extra>
        <a @click="handleCopy">复制</a>
        <Divider type="vertical" class="action-divider" />
        <a @click="handleDelete">删除</a>
      </template>


      <div v-if="data.show">
        <div class="no-collapse-form-item">
          <div class="item-label">服务</div>
          <div style="width: 200px;">

            <ApiSelect
              :api="resourceApi.listAllInstance"
              v-model:value="iamCode" 
              showSearch placeholder="请选择"
              @change="handleSelectService"
              optionFilterProp="label"
              resultField="data"
              labelField="serviceSummary"
              valueField="iamCode"
            />
          </div>
        </div>
        <Collapse v-model:activeKey="activeKey" accordion :bordered="false" ghost>
          <CollapsePanel key="2" :collapsible="data.actionCollapsible">
            <template #header>
              <span class="item-label">
                操作
              </span>

              <span class="collapse-header-desc" v-if="policyStatement[data.statementIndex].actions.length > 0">
                <a>已选 {{ policyStatement[data.statementIndex].actions.length }} 操作</a>
              </span>
            </template>

            <div class="form-item">
              <ApiPermission 
                v-model:actions="policyStatement[data.statementIndex].actions"
                :iamCode="iamCode"
                :namespaceCode="namespaceCode"
                @change="handleSelectActions"
              />
            </div>
          </CollapsePanel>
        </Collapse>
      </div>

      <template #title>
        <div style="width: 100%; cursor: pointer;" @click="handleChangeShow()">
          <TypographyText :content="data.title"  />
        </div>
      </template>
    </Card>
  </div>
</template>
<script lang="ts" setup>
import { ref, useAttrs, onMounted, watch, unref } from "vue";
import { useDesign } from "/@/hooks/web/useDesign"
import { ApiSelect } from "/@/components/Form/index"
import { Card, Typography, Divider, CollapsePanel, Collapse } from "ant-design-vue"
import ApiPermission from './ApiPermission.vue'
import * as resourceApi from "/@/api/iam/resource"

const CardMeta = Card.Meta
const TypographyText = Typography.Text
const { prefixCls } = useDesign("policy-statement")
const emit = defineEmits(['copy', 'delete', 'change-statement-list']);
const attrs = useAttrs();
const activeKey = ref()
const iamCode = ref()
interface Statement {
  actions: string[]
  condition: object
}

const props = defineProps({
  index: { type: Number, required: true },
  policyStatement: { type: Array  as PropType<Statement[]>, required: true, default: () => [
    {
      actions: [], condition: {}
    }
  ]},
  namespaceCode: { type: String, required: false },
  data: { type: Object, required: false, default: () => {
    return {
      show: true,
      title: '选择服务',
      actionCollapsible: 'disabled',
      statementIndex: 0
    }
  }},
})

const initIamCode = () => {
  console.log('props.data', props)
  if (props.policyStatement.length <= 0 || !props.data || iamCode.value) {
    return
  }
  const actions = props.policyStatement[props.data.statementIndex].actions
  iamCode.value = actions.length > 0 ? actions[0].split(':')[0] : null
}

watch(
  () => props.policyStatement,
  () => {
    initIamCode()
  },
  { deep: true, immediate: true },
);


const handleChangeShow = () => {
  props.data.show = !props.data.show;
}

const handleSelectService = (v) => {
  props.data.actionCollapsible = null
  props.data.title = '选择操作'
  props.policyStatement[props.data.statementIndex] = {
    actions: [],
    condition: {}
  }
}

const handleSelectActions = (actions) => {
  props.data.title = `${iamCode.value} / ${actions.length}个操作`
  const oldValue = props.policyStatement[props.data.statementIndex]
  props.policyStatement[props.data.statementIndex] = { ...oldValue, actions }
  emit('change-statement-list', [
    ...unref(props.policyStatement)
  ])
}

const handleCopy = () => emit('copy', JSON.parse(JSON.stringify(props.data)), props.index)
const handleDelete = () => emit('delete', props.index)

</script>

<style lang="less">
 @prefix-cls: ~"@{namespace}-policy-statement";

.@{prefix-cls} {
  padding: 5px;
 
  .ant-card-head {
    background-color: #F7F9FA !important;
  }

  .ant-select {
    width: 100% !important;
  }

  .item-label {
    box-sizing: border-box;
    width: 50px;
    padding-right: 10px;
    cursor: pointer;
  }
  .form-item {
    margin-left: 22px;
  }

  .collapse-header-desc {
    margin-left: 10px;
  }

  .no-collapse-form-item {
    display: flex;
    align-items: center;
    margin-left: 40px;
    width: 100%
  }
}
</style>
